package com.softstao.guoyu.ui.activity.me;

import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.me.RebateCondition;
import com.softstao.guoyu.model.me.RebateDetail;
import com.softstao.guoyu.model.sale.OrderGoods;
import com.softstao.guoyu.mvp.interactor.me.RebateInteractor;
import com.softstao.guoyu.mvp.presenter.me.RebatePresenter;
import com.softstao.guoyu.mvp.viewer.me.RebateDetailViewer;
import com.softstao.guoyu.ui.adapter.OrderGoodsAdapter;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewBaseAdapter;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewHolder;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.CircleImageView;
import com.softstao.softstaolibrary.library.widget.CustomScrollerView;
import com.softstao.softstaolibrary.library.widget.EmptyLayout;
import com.softstao.softstaolibrary.library.widget.FullyLinearLayoutManager;
import com.softstao.softstaolibrary.library.widget.MarginDecoration2;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * Created by vaikus on 2017/7/21.
 */

public class RebateDetailActivity extends BaseActivity implements RebateDetailViewer {

    @AIPresenter(presenter = RebatePresenter.class, interactor = RebateInteractor.class)
    RebatePresenter presenter;

    @BindView(R.id.avatar)
    CircleImageView avatar;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.level)
    TextView level;
    @BindView(R.id.mobile)
    TextView mobile;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.search_v)
    EditText searchView;
    @BindView(R.id.list_view)
    RecyclerView listView;
    @BindView(R.id.more)
    TextView more;
    @BindView(R.id.scroll_view)
    CustomScrollerView scrollView;
    @BindView(R.id.loading)
    RelativeLayout loading;
    @BindView(R.id.empty_layout)
    EmptyLayout emptyLayout;
    private int id, type;
    private String month,keyword;
    private RebateCondition condition = new RebateCondition();
    private RebateDetail rebateDetail;
    private List<RebateDetail.OrderListBean> orderList = new ArrayList<>();
    private RecycleViewBaseAdapter<RebateDetail.OrderListBean> adapter;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public int _ContentView() {
        return R.layout.activity_rebate_detail;
    }

    @Override
    public void initView() {
        initTitle("返利详情");
        id = getIntent().getIntExtra("id", 0);
        type = getIntent().getIntExtra("type", 0);
        month = getIntent().getStringExtra("month");
        scrollView.setOnScrollChangedListener(this);
        search();

        adapter = new RecycleViewBaseAdapter<RebateDetail.OrderListBean>(orderList,R.layout.layout_order_list_item) {
            @Override
            public void convert(RecycleViewHolder holder, RebateDetail.OrderListBean orderListBean) {
                holder.getView(R.id.right).setVisibility(View.GONE);
                holder.getView(R.id.bottom).setVisibility(View.GONE);
                holder.getView(R.id.rebate_agent).setVisibility(View.VISIBLE);
                holder.setText(R.id.total_price_view,"合计返利：")
                        .setText(R.id.order_sn,"订单编号：" + orderListBean.getOrderCode())
                        .setText(R.id.time,"时间：" + format.format(new Date(orderListBean.getDate())))
                        .setText(R.id.from_agent,"订货人：" + orderListBean.getOrderer())
                        .setText(R.id.total_price,getResources().getString(R.string.rmb) + LZUtils.priceFormat(orderListBean.getMoney()))
                        .setText(R.id.rebate_agent,"帮TA返利人：" + orderListBean.getRebateAgent() + "(" + orderListBean.getLevel() + ")");
                RecyclerView recyclerView = holder.getView(R.id.list_view);
                OrderGoodsAdapter adapter;
                if (orderListBean.getProductList()==null){
                    adapter = new OrderGoodsAdapter(new ArrayList<OrderGoods>());
                }else {
                    adapter = new OrderGoodsAdapter(orderListBean.getProductList());
                }
                recyclerView.setTag(adapter);
                recyclerView.setAdapter(adapter);
                recyclerView.setLayoutManager(new FullyLinearLayoutManager(holder.itemView.getContext()));
            }
        };
        listView.setAdapter(adapter);
        listView.setLayoutManager(new FullyLinearLayoutManager(this));
        listView.addItemDecoration(new MarginDecoration2(this));
    }

    private void search() {
        searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        searchView.setInputType(EditorInfo.TYPE_CLASS_TEXT);
        searchView.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                try {
                    keyword = URLEncoder.encode(searchView.getText().toString(), "utf-8");
                    currentPage = 1;
                    findDetail();
                    InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return false;
            }
            return true;
        });
    }

    private void initData() {
        if (rebateDetail.getAvatar() != null && !rebateDetail.getAvatar().equals("")) {
            Glide.with(context).load(rebateDetail.getAvatar()).into(avatar);
        } else {
            avatar.setImageResource(R.mipmap.default_avatar);
        }
        name.setText(rebateDetail.getName());
        level.setText(rebateDetail.getLevel());
        mobile.setText(rebateDetail.getMobile());
        money.setText(Html.fromHtml("当月返利：<font color='#fb4a9b'>" + LZUtils.priceFormat(rebateDetail.getMoney()) + "元</font>"));

        if (rebateDetail.getOrderList() != null && rebateDetail.getOrderList().size() != 0) {
            more.setVisibility(View.GONE);
            emptyLayout.setVisibility(View.GONE);
            if (currentPage == 1) {
                orderList.clear();
            }
            orderList.addAll(rebateDetail.getOrderList());
            adapter.notifyDataSetChanged();
        } else {
            if (currentPage == 1) {
                orderList.clear();
                emptyLayout.setVisibility(View.VISIBLE);
            } else {
                more.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        findDetail();
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        findDetail();
    }

    @Override
    public void onLoad() {
        super.onLoad();
        findDetail();
    }

    @Override
    public void findDetail() {
        loading.setVisibility(View.VISIBLE);
        switch (type) {
            case 1:
                condition.setRelaAgentId(id);
                break;
            case 2:
                condition.setSubAgentId(id);
                break;
        }
        condition.setAgentId(SharePreferenceManager.getInstance().getAgentId());
        condition.setMonth(month.replace("年", "-").replace("月", ""));
        condition.setSearch(keyword);
        presenter.getDetail(currentPage, type, condition);
    }

    @Override
    public void getDetail(RebateDetail rebateDetail) {
        loading.setVisibility(View.GONE);
        if (rebateDetail != null) {
            this.rebateDetail = rebateDetail;
            initData();
        }
    }
}
